package com.example.springstack.springboot.spring5.action;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @author qiangfanghao
 * @date
 */
@RestController
@RequestMapping("/acs")
@Slf4j
public class PropertiesController {

    /**
     * 操作 properties文件
     * @throws IOException
     * @throws ConfigurationException
     */
    @PostMapping("/config/PropertiesServlet")
    public void propertiesServlet(HttpServletRequest request) throws IOException, ConfigurationException {
        String localAddr = request.getLocalAddr();
        int localPort = request.getLocalPort();

        PropertiesConfiguration config = new PropertiesConfiguration();
        String filePath = Thread.currentThread().getContextClassLoader().getResource("config.properties").getPath();

        config.read(new FileReader(filePath));
        String string = config.getString("mongo.replset");
        //一定要判断是否存在 属性值 ,添加不存在的属性值会导致配置文件错乱
        boolean b = config.containsKey("1234");
        if (b){
            config.setProperty("1234","qwer1234");
        }

        boolean b2 = config.containsKey("mongo.replset");
        if (b2){
            config.setProperty("mongo.replset","qwer1234");
        }

        //指定字符集编码
//        config.write(new BufferedWriter (new OutputStreamWriter (new FileOutputStream (filePath),"Unicode")));

        config.write(new FileWriter(filePath));
        log.debug(string);
    }
}
